<template>
	<view v-if="getRequestOK">
		
		<unicloud-db ref="udb" :where="sWhere" v-slot:default="{data, loading, error, options}" :collection="colList"
		loadtime="manual" >
			<view v-if="error">{{error.message}}</view>
			<view v-else>
				<view class="feed-user">
					<u-avatar size="60" :src="data[0].user_id[0].avatar_file.url"></u-avatar>
					<view class="info">
						<text>{{ data[0].user_id[0].nickname }}</text>
						
					</view>
				</view>
				<view class="feed-info">
					<view class="title" v-if="!!data[0].content">{{ data[0].content }}</view>
					<view id="contact" v-if="!!data[0].contacts" class="contact">联系方式：{{data[0].contacts}}</view>
					<image class="feed-imgs" mode="widthFix" v-for="(image, index) in data[0].imgs" :key="index" :src="image.url" @tap="previewImage(index,data[0].imgs)" />
					<!-- 4.13 添加修改图标按钮，点击跳转到修改页面，参数：帖子ID，帖子内容 标题-->
					<view >
						<u-icon labelPos="left" name="edit-pen" color="#2979ff" size="28"
						@click="toEdit(data[0]._id,data[0].content,data[0].title)"></u-icon>
					</view>
					<view class="other">
						<uni-dateformat :date="data[0].publish_date  - 7200000"></uni-dateformat>
						<text>{{ data[0].view_count}} 阅读 {{ data[0].like_count}} 点赞</text>
					</view>
					</view>
		</view>
		</unicloud-db>
		<hb-comment ref="hbComment" @add="add" @del="del" @like="like"  :deleteTip="'确认删除？'"
		    :cmData="commentData" v-if="commentData"></hb-comment>
		
	</view>
</template>
 
<script>
	// 引入 时间日期格式化显示函数
	import timeFrom from '@/tools/timeFrom.js'
	const db = uniCloud.database()
	export default {
		data() {
			return {
				sWhere:'',
				// 数据请求状态
				getRequestOK: false,
				// 动态详情
				InquiryInfo: {},
				colList: [
					db.collection("NeuHelper-Posts")
						.field('content,_id,user_id,title,view_count,publish_date,like_count,imgs,contacts').getTemp(),
					db.collection('uni-id-users').field('_id,nickname,avatar_file').getTemp()
				], //.where("category_id == '642d7f6ce766bb2975cd4df7'")
				commentData:{},
				postID:'', // 当前帖子ID
				current_userID:'' ,// 当前登录用户ID
				editOK:false,
				current_post_userID:'' // 当前帖子用户ID
			}
		},
		// options 为传递过来的日常资讯的ID,为一个对象，里边有帖子相关的信息
		async onLoad(options) {
			console.log("typeof options: ", typeof options);
			this.postID = options; 
			// #ifdef MP-WEIXIN
			// 微信条件下分享到朋友圈、群组
			wx.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline']
			})
			// #endif
			// udb中设置manual 为true之后，不会在页面初始化的时候加载数据，因此可以在页面加载
			//时对查询数据进行处理 ， 只查询当前帖子
			this.sWhere = "_id == '" + options.id + "'"
			
			await this.getCurrentUserID() // 获取当前用户ID ,异步需要await 等待结果
			await this.getPostUserID()
			console.log('bug')
			console.log(this.current_userID)
			console.log(this.current_post_userID)
			
			// 发布新的评论后，触发数据更新
			uni.$on("add", commentContent =>{
				this.commentData = {}
				console.log("触发添加事件")
				console.log(commentContent)
				this.addcomment(commentContent,options) // 添加新的评论
			//	this.getComment(options)
			})
			// 获取帖子评论列表
			this.getComment(options)
			// 如果当前登录用户ID与帖子用户ID 一致才允许修改
			this.getRequestOK = true
		//	if(this.current_userID == this.current_post_userID )this.editOK = true;
			// 组件上配置了 loadtime = "manual", 这里需要手动加载数据
			// Modified 0414 1840
			//设置本地阅读记录缓存
			this.readLogArray = uni.getStorageSync('readLog') || ["null"];
			// [{post_id: "null", last_time: Date.now()}]
			console.log("readLogArray", this.readLogArray);
			// if (this.readLogArray != []) {
			// 	this.readLogArray = JSON.parse(this.readLogArray);
			// } //不需要先经过JSON.parse()
			console.log("options.id: ", options.id);
			if (!this.readLogArray.includes(options.id)) {
				this.readLogArray.push(options.id);
			}
			console.log(this.readLogArray);
			uni.setStorageSync('readLog', this.readLogArray);
			
			this.$nextTick(() => {
			  this.$refs.udb.loadData()
			})
			
			// console.log(this.feedInfo)
		},
		filters: {
			timeFormate(timeDate) {
				let Time = new Date(timeDate);
				let timestemp = Time.getTime();
				let t = timeFrom(timestemp, "yyyy年mm月dd日");
				return t;
			}
		},
		// 4.13 顶部下拉事件
		onPullDownRefresh() {
			console.log('顶部下拉刷新')
			//4.14 刷新帖子内容
			this.$refs.udb.loadData({
					clear: true
				}, () => {
					// 停止下拉刷新
					uni.stopPullDownRefresh()
				})
			// 刷新评论
			this.commentData = {}
			this.$forceUpdate();
			this.getComment(this.postID); // 重新获取评论数据
		},
		methods: {
			async getPostUserID(){
				let userID =await db.collection("NeuHelper-Posts").where("_id=='" + this.postID.id  + "'").field("user_id").get()
				userID = userID.result.data[0].user_id
				this.current_post_userID = userID
			},
			async getCurrentUserID(){
				let userID =await db.collection("uni-id-users").where("_id == $cloudEnv_uid").field("_id").get()
				userID = userID.result.data[0]._id 
				this.current_userID = userID
			},
			navigateTo(url) {
				
				uni.navigateTo({
					url: url
				});
			},
			toEdit(post_id,post_content,post_title){
				console.log('跳转编辑') 
				//4.14  如果无法不发发帖本人则无法修改
				if(this.current_userID != this.current_post_userID){
					uni.showToast({
						icon: 'none',
						title: '禁止编辑',
						duration: 1000
					})
				}else 
					this.navigateTo('edit?postId=' + post_id+ '&post_content=' + post_content+ '&post_title=' + post_title );
			},
			//图片预览
			previewImage(image_index,imageList,) {
				// 传递过来的 imageList 是一个有图片url的对象，需要先提取
				let imgs = []
				for(var i = 0 ; i < imageList.length; ++i )imgs.push(imageList[i].url)
				var current = imgs[image_index];
				uni.previewImage({
				current:current,
				urls: imgs,
				fail: function(err) {
				console.log(err.errMsg);
				}
				});
			},
			/** 
			 * 添加新的评论
			 * @param {Object} commentContent
			 * @param {Object} options
			 */
			async addcomment(commentContent, options){
				console.log("开始添加")
				const db1 =  uniCloud.databaseForJQL()
				const db2 =  uniCloud.databaseForJQL()
				let dataUser = await  db1.collection('uni-id-users').where("_id == $cloudEnv_uid "). field('_id,nickname,avatar_file').get()
				console.log(dataUser)
				dataUser = dataUser.data[0]  // 获取用户头像，昵称，该评论的观看数量
				
				console.log(dataUser)
				console.log(options)
				console.log(commentContent)
				try {
					await db2.collection('NeuHelper-PostComments').add({
						post_id:options.id,
						user_id:dataUser._id,
						user_avatar:dataUser.avatar_file.url,
						user_nickname:dataUser.nickname,
						comment_content:commentContent,
						like_count:0
					})
				} catch (e) {
					uni.showModal({
						title: '提示',
						content: e.message
					})
				}
				let postData = await db1.collection('NeuHelper-Posts').where("_id=='" + options.id  + "'"). field('user_id').get()
				    // console.log(postData)
				    postData = postData.data[0]  
				    // 将评论消息推送到发布帖子的用户
				    if(dataUser._id != postData.user_id ){
				     try {
				      await db2.collection('NeuHelper-Notifications').add({
				       post_id:options.id, 
				       toNotify_id:postData.user_id, // 发帖人的ID
				       initiator_id:dataUser._id, // 评论人的ID
				       type:0// 评论类型
				      })
				     } catch (e) {
				      uni.showModal({
				       title: '提示',
				       content: e.message
				      })
				     }
				    }
				
				uni.showToast({
					title: "评论发表成功",
					icon: "success",
					duration: 1000,
				});
			},
			// 获取帖子评论列表 options 为当前帖子ID
			async getComment(options){
				// db 组件的查询条件
				this.sWhere = "_id=='" + options.id  + "'"
				const db =  uniCloud.databaseForJQL()
				const db2 =  uniCloud.databaseForJQL()
				console.log("帖子ID")
				console.log(options.id )
				let dataPost = await db.collection("NeuHelper-Posts").where("_id =='" + options.id  + "'").get()
				dataPost = dataPost.data[0]  // 获取用户头像，昵称，该评论的观看数量
				console.log("帖子信息")
				console.log(dataPost)
				let commentList = await db2.collection("NeuHelper-PostComments").where("post_id =='" + options.id  + "'")
				 .orderBy('comment_date asc').get()
				commentList = commentList.data  // 获取该帖子下的评论
				console.log(commentList)
				this.commentData = {
				    "readNumer": dataPost.view_count,
				    "commentSize": commentList.length,
				    "comment": commentList
				}
				this.addViewCount(options,dataPost.view_count) // 阅读数量+1
			},
			// 帖子阅读数量+1
			async addViewCount(options,view_count){
				const db2 =  uniCloud.databaseForJQL()
				try {
					await db2.collection("NeuHelper-Posts").where("_id=='" + options.id  + "'").update({'view_count':view_count +1})
				} catch (e) {
					uni.showModal({
						title: '提示',
						content: e.message
					})
				}
			}
			
		}
	}
</script>

<style lang="scss" scoped>
	.feed-user {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: flex-start;
		align-items: center;
		align-content: center;
		margin: 20upx 0 0 25upx;

		.info {
			display: flex;
			flex-direction: column;
			flex-wrap: wrap;
			justify-content: flex-end;
			align-items: left;
			margin-left: 20upx;
			font-size: 30upx;
			font-weight: bolder;
			color: #1f2046;
		}
	}

	.feed-info {
		width: 700upx;
		margin-top: 20upx;
		margin-left: 25upx;
		text-align: center;
		padding-bottom: 10upx;

		.title {
			font-size: 32upx;
			margin-bottom: 30upx;
			text-align: left;
			line-height: 52upx;
			color: #666;
		}

		.feed-imgs {
			margin: 5upx 0;
			width: 100%;
		}
		.contact{
			text-align: left;
		}
		.other {
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
			justify-content: space-between;
			align-items: center;
			align-content: center;
			padding: 40upx 0 20upx;
			font-size: 24upx;
			color: #888;

			.micon {
				padding: 10upx 20upx;
			}
		}
	}

	.line {
		height: 30upx;
		width: 750upx;
		background-color: #f3f3f3;
	}
</style>
